package com.spark.trouble.handle

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.report
import com.spark.common.ext.success
import com.spark.common.ext.wrapIO
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.trouble.R
import com.spark.trouble.model.HTLevelModel
import com.spark.trouble.model.RespUnitModel
import kotlinx.android.synthetic.main.frag_choose_choice.*

/**
 * 选择 隐患等级/责任单位
 */
class ChooseChoiceFragment : BaseFragment() {
    private lateinit var choiceAdapter: ChoiceAdapter
    private var currPage = 1
    private var totalPage = 1
    private var type = 0

    private var levels: MutableList<HTLevelModel.ResultMap> = mutableListOf()
    private var units: MutableList<RespUnitModel.ResultMap> = mutableListOf()
    private var strs: MutableList<String> = mutableListOf()

    companion object {
        // 隐患等级
        val htLevel = 0
        // 责任单位
        val unit = 1

        val resHTLevel = 0x10001
        val resUnit = 0x10002

        fun newInstance(type: Int): ChooseChoiceFragment {
            val fragment = ChooseChoiceFragment()
            val args = Bundle()
            args.putInt("type", type)
            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_choose_choice
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            type = getInt("type")
        }
        iv_back.setOnClickListener { pop() }
        tv_title.text = if (type == htLevel) "选择隐患等级" else "选择责任单位"

        choiceAdapter = ChoiceAdapter(R.layout.item_choice).apply {
            setOnItemClickListener { adapter, view, position ->
                when (type) {
                    htLevel -> {
                        val bundle = Bundle()
                        bundle.putString("level", levels[position].name)
                        setFragmentResult(resHTLevel, bundle)
                        pop()
                    }
                    unit -> {
                        val bundle = Bundle()
                        val result = units[position]
                        bundle.putString("unit", Gson().toJson(result))
                        setFragmentResult(resUnit, bundle)
                        pop()
                    }
                }
            }
        }
        recy_choices.apply {
            adapter = choiceAdapter
            layoutManager = LinearLayoutManager(context)
        }
        refresh_layout.apply {
            setOnRefreshListener {
                currPage = 1
                fetchData(currPage)
            }
            setOnLoadmoreListener {
                if (currPage > totalPage) {
                    success("没有更多数据了")
                    finishLoadmore()
                } else {
                    currPage++
                    fetchData(currPage)
                }
            }
        }
        fetchData(currPage)
    }

    @SuppressLint("CheckResult")
    private fun fetchData(page: Int) {
        val url = if (type == htLevel) "${Const.base_url}${Const.act_select_ht_level}" else "${Const.base_url}${Const.act_select_responsible_unit}"
        Http.request()
                .rxPost(url, "{}".toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            val gson = Gson()
                            if (type == htLevel) {
                                gson.fromJson(it, HTLevelModel::class.java)?.apply {
                                    if (code == "200") {
                                        if (page == 1) {
                                            levels.clear()
                                            choiceAdapter.data.clear()
                                            strs.clear()
                                        }
                                        levels.addAll(this.resultMaps)
                                        this.resultMaps.forEach {
                                            strs.add(it.name)
                                        }
                                        choiceAdapter.addData(strs)
                                    }
                                }
                            } else {
                                gson.fromJson(it, RespUnitModel::class.java)?.apply {
                                    if (code == "200") {
                                        if (page == 1) {
                                            units.clear()
                                            choiceAdapter.data.clear()
                                            strs.clear()
                                        }
                                        units.addAll(this.resultMaps)
                                        this.resultMaps.forEach {
                                            strs.add(it.name)
                                        }
                                        choiceAdapter.addData(strs)
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            refresh_layout.apply { if (page == 1) finishRefresh() else finishLoadmore() }
                        },
                        {
                            refresh_layout.apply { if (page == 1) finishRefresh() else finishLoadmore() }
                        },
                        {
                            dispose = it
                        }
                )
    }

}

class ChoiceAdapter(layoutRes: Int) : BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: String?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_choice, item)
            setGone(R.id.divider, adapterPosition != data.size - 1)
        }
    }
}